package cn.org.xwb.main.service.impl;

import cn.org.xwb.main.constants.ResponseConstant;
import cn.org.xwb.main.dto.BaseRespResult;
import cn.org.xwb.main.dto.RsaKeyPair;
import cn.org.xwb.main.dto.ServerErrorRespResult;
import cn.org.xwb.main.dto.SuccessRespResult;
import cn.org.xwb.main.service.RsaService;
import cn.org.xwb.main.utils.HttpUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * RSA 相关的业务层
 */
@Service
@Log4j2
public class RSAServiceImpl implements RsaService {

    /**
     * 通用的 RSA 密钥对
     */
    @Autowired
    private RsaKeyPair rsaCommonKeyPair;

    /**
     * 向客户端发送通用的 RSA 公钥
     *
     * @return 通用的 RSA 公钥
     */
    @Override
    public BaseRespResult<Object> sendRsaCommonPublicKey(HttpServletRequest request) {
        String rsaCommonPublicKey = rsaCommonKeyPair.getPublicKey();
        if (Objects.isNull(rsaCommonPublicKey) || rsaCommonPublicKey.isEmpty()) {
            log.error("客户端 {} 获取通用的 RSA 公钥失败，原因：通用的 RSA 公钥为空", HttpUtil.getClientHostIpPort(request));
            return ServerErrorRespResult.serverErrorRespResult(ResponseConstant.GET_RSA_COMMON_PUBLIC_KEY_FAIL);
        }
        log.info("客户端 {} 获取通用的 RSA 公钥成功", HttpUtil.getClientHostIpPort(request));
        return SuccessRespResult.successRespResult(ResponseConstant.GET_RSA_COMMON_PUBLIC_KEY_SUCCESS, rsaCommonPublicKey);
    }
}
